﻿using System.Drawing;
using System.Linq;
using CloudShot.Editor;

namespace CloudShot.ViewModels
{
  class BackColorPropertyHandler : RadioButtonPropertyHandler<Color?>
  {
    private byte? _initialOpacity;
    private Color? _initialBorderColor;
    private Color? _initialTextColor;

    private readonly byte _previewOpacity;
    private readonly FigureColorScheme[] _colorSchemes;


    public BackColorPropertyHandler(byte previewOpacity, FigureColorScheme[] colorSchemes)
      : base((m) => m.BackColor)
    {
      _previewOpacity = previewOpacity;
      _colorSchemes = colorSchemes;
    }

    public override void SetViewModel(PropertiesFormViewModel viewModel)
    {
      base.SetViewModel(viewModel);

      if (viewModel != null)
      {
        _initialBorderColor = viewModel.BorderColor;
        _initialOpacity = viewModel.BackgroundOpacity;
        _initialTextColor = viewModel.TextColor;
      }
    }

    protected override void PreviewInternal(Color? previewValue)
    {
      if (_initialOpacity == 0)
        ViewModel.BackgroundOpacity = _previewOpacity;

      ViewModel.TextColor = GetTextColor(previewValue);
      ViewModel.BorderColor = GetBorderColor(previewValue);
      base.PreviewInternal(previewValue);
    }


    protected override void ResetInternal()
    {
      if (_initialOpacity == 0)
        ViewModel.BackgroundOpacity = 0;

      ViewModel.BorderColor = _initialBorderColor;
      ViewModel.TextColor = _initialTextColor;
      base.ResetInternal();
    }

    protected override void SetPropertyInternal(Color? value)
    {
      if (_initialOpacity == 0)
      {
        _initialOpacity = _previewOpacity;
        ViewModel.BackgroundOpacity = _previewOpacity;
      }

      _initialBorderColor = GetBorderColor(value);
      _initialTextColor = GetTextColor(value);

      ViewModel.BorderColor = _initialBorderColor;
      ViewModel.TextColor = _initialTextColor;

      base.SetPropertyInternal(value);
    }

    private Color? GetTextColor(Color? backColorValue)
    {
      FigureColorScheme figureColorScheme = _colorSchemes.FirstOrDefault(p => p.BackColor == backColorValue);
      return figureColorScheme == null ? (Color?)null : figureColorScheme.TextColor;
    }

    private Color? GetBorderColor(Color? backColorValue)
    {
      FigureColorScheme figureColorScheme = _colorSchemes.FirstOrDefault(p => p.BackColor == backColorValue);
      return figureColorScheme == null ? (Color?)null : figureColorScheme.BorderColor;
    }
  }
}
